package o2o.web.actions.user;

import com.jinyou.utils.common.*;
import o2o.business.device.AppDeviceInfoBusiness;
import o2o.cache.agent.CityAgentMemory;
import o2o.cache.user.UserAddressMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.agent.CityAgent;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.user.UserAddress;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.user.UserAddressDBVO;
import o2o.dao.VO.user.UserAddressVO;
import o2o.system.data.PROMPTS;
import o2o.utils.CommonUtils;
import o2o.utils.MultilingualResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

//用户收货地址
@Controller
public class UserAddressAction {

    //获取收货地址
    @RequestMapping(method = RequestMethod.POST, value = "/user/address/list")
    @ResponseBody
    public String getUserAddressList(String token, String lang) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        List<UserAddress> list = UserAddressMemory.getInstance().listOfUser(user.getUsername());
        if (null == list || list.size() <= 0) {
            return AjaxResult.successResult(0, null);
        }

        // // 排序  新添加的在上面
        // Collections.sort(list, Comparator.comparingLong(UserAddress::getCreateTime));

        // 排序  默认地址在最前面 然后是 最后修改的在前面
        Comparator<UserAddress> isDefault = Comparator.comparing(UserAddress::getIsDefault).reversed();
        Comparator<UserAddress> updateTime = Comparator.comparing(UserAddress::getUpdateTime).reversed();
        list.sort(isDefault.thenComparing(updateTime));

        List<UserAddressVO> voList = new ArrayList<UserAddressVO>();
        for (int i = 0; i < list.size(); i++) {
            UserAddressVO userAddressVO = new UserAddressVO();
            try {
                ObjectUtils.copyPropertiesExclude(list.get(i), userAddressVO, null);
            } catch (Exception e) {
                e.printStackTrace();
//                AjaxResult.errorResult("获取用户收货地址出错，请稍后再试");
                MultilingualResult.errorResultV2(PROMPTS.ERROR_GET_ADDRESS, lang);
            }
            voList.add(userAddressVO);
        }
        if (null == voList) {
            return AjaxResult.successResult(0, null);
        }
        return AjaxResult.successResult(voList.size(), voList);
    }

    //添加收货地址
    @RequestMapping(method = RequestMethod.POST, value = "/user/address/add")
    @ResponseBody
    public String addUserAddress(String token, UserAddressDBVO userAddress, Integer needInfo, String lang, String devJson) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNull(userAddress.getAddress()) && ValidateUtil.isID(userAddress.getAgentId())) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(userAddress.getAgentId());
            if (null != cityAgent) {
                userAddress.setAddress(cityAgent.getName());
                userAddress.setLat(cityAgent.getLat());
                userAddress.setLng(cityAgent.getLng());
                userAddress.setAreaPoint(cityAgent.getAreaPoint());
                userAddress.setGeocode(cityAgent.getGeocode());
            } else {
                return MultilingualResult.errorResultV2(PROMPTS.INFORMATION_IS_WRONG, lang);
            }
        }

        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLat()) && ValidateUtil.isID(userAddress.getAgentId())) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(userAddress.getAgentId());
            if (null != cityAgent) {
                userAddress.setAddress(cityAgent.getName());
                userAddress.setLat(cityAgent.getLat());
                userAddress.setLng(cityAgent.getLng());
                userAddress.setAreaPoint(cityAgent.getAreaPoint());
                userAddress.setGeocode(cityAgent.getGeocode());
            }
        }


        //验证输入
        try {
            validateInfo(userAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.toString());
        }

        //todo 等我5分钟需要判断收货地址的城市不能为空

//        StringBuilder sql = new StringBuilder();
//        sql.append("INSERT INTO ").append(PojoTables.UserAddress).append(" (username,buyer,telephone,address,address2,lng,lat,province,city,county,delflag,createtime,createuser) ")
//                .append("VALUE('")
//                .append(user.getUsername()).append("','")
//                .append(userAddress.getBuyer()).append("','")
//                .append(userAddress.getTelephone()).append("','")
//                .append(userAddress.getAddress()).append("','")
//                .append(userAddress.getAddress2()).append("',")
//                .append(userAddress.getLng()).append(",")
//                .append(userAddress.getLat()).append(",'")
//                .append(userAddress.getProvince()).append("','")
//                .append(userAddress.getCity()).append("','")
//                .append(userAddress.getCounty()).append("',0,")
//                .append(DateUtils.getCurrTime()).append(",")
//                .append(user.getUsername()).append(")");
//
//        try {
//            UserDaoSql.getInstance().executeBySql(sql.toString());
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("新增收货地址失败,请稍后再试");
//        }

        if (ValidateUtil.isLatLng(userAddress.getLat(), userAddress.getLng())) {
            String geocode = Geohash.encode(userAddress.getLat(), userAddress.getLng());
            Long areaPoint = Geohash.getArea(userAddress.getLat(), userAddress.getLng());
            userAddress.setGeocode(geocode);
            userAddress.setAreaPoint(areaPoint);
        }

        userAddress.setUsername(user.getUsername());
        userAddress.setCreateTime(DateUtils.getCurrTime());
        userAddress.setDelFlag(0);
        userAddress.setCreateUser(user.getUsername());

        if (ValidateUtil.isNotNull(userAddress.getAddress3()) && "null".equalsIgnoreCase(userAddress.getAddress3())) {
            userAddress.setAddress3("");
        }
        // 默认地址处理
        List<UserAddress> userAddressList = UserAddressMemory.getInstance().listOfUser(user.getUsername());
        List<UserAddress> defaultUserAddressList = new ArrayList<>();
        if (userAddress.getIsDefault() == 1 && ValidateUtil.isAbsList(userAddressList)) {
            if (ValidateUtil.isAbsList(userAddressList)) {
                for (UserAddress u : userAddressList) {
                    if (u != null && u.getIsDefault() == 1) {
                        defaultUserAddressList.add(u);
                    }
                }
            }
        }
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection();
            con.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return MultilingualResult.errorResultV2(PROMPTS.INFORMATION_SAVE_FAILED, lang);
        }
        long id = 0l;
        try {
            if (defaultUserAddressList.size() > 0) {
                cancelDefaultAddress(user.getUsername(), user.getUsername(), con);
            }
            id = UserDaoSql.getInstance().saveObj(PojoTables.UserAddress, userAddress, con);
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return MultilingualResult.errorResultV2(PROMPTS.INFORMATION_SAVE_FAILED, lang);
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        //处理缓存
        UserAddressMemory.getInstance().addUserAddress(user.getUsername());
        if (defaultUserAddressList.size() > 0) {
            for (UserAddress u : defaultUserAddressList) {
                UserAddressMemory.getInstance().modifyUserAddress(u.getId());
            }
        }

        if (ValidateUtil.isNotNull(devJson)) {// 设备信息
            AppDeviceInfoBusiness.userAddDevice(user.getUsername(), devJson);
        }

        // 前端解析不出来  如果使用 大于版本不会出现这个问题
        if (needInfo != null && needInfo > 0) {
            UserAddress info = UserAddressMemory.getInstance().getAddressInfo(id);
            if (info != null) {
                UserAddressVO userAddressVO = new UserAddressVO();
                BeanUtils.copyProperties(info, userAddressVO);
                return AjaxResult.successResult(userAddressVO);
            }
        }
        return AjaxResult.successResult();
    }

    //修改收货地址
    @RequestMapping(method = RequestMethod.POST, value = "/user/address/modify")
    @ResponseBody
    public String modifyUserAddress(String token, UserAddressDBVO userAddress, String lang) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == userAddress.getId() || userAddress.getId() <= 0) {
            return MultilingualResult.errorResultV2(PROMPTS.CHOOSE_YOUR_ADDRESS, lang);
        }

        if (ValidateUtil.isNull(userAddress.getAddress()) && ValidateUtil.isID(userAddress.getAgentId())) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(userAddress.getAgentId());
            if (null != cityAgent) {
                userAddress.setAddress(cityAgent.getName());
            } else {
                return MultilingualResult.errorResultV2(PROMPTS.INFORMATION_IS_WRONG, lang);
            }
        }

        if (ValidateUtil.isNotLatLng(userAddress.getLat(), userAddress.getLat()) && ValidateUtil.isID(userAddress.getAgentId())) {
            CityAgent cityAgent = CityAgentMemory.getInstance().getById(userAddress.getAgentId());
            if (null != cityAgent) {
                userAddress.setAddress(cityAgent.getName());
                userAddress.setLat(cityAgent.getLat());
                userAddress.setLng(cityAgent.getLng());
                userAddress.setAreaPoint(cityAgent.getAreaPoint());
                userAddress.setGeocode(cityAgent.getGeocode());
            }
        }

        //验证输入
        try {
            validateInfo(userAddress);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.toString());
        }

        String latLng = "";
        if (ValidateUtil.isLatLng(userAddress.getLat(), userAddress.getLng())) {
            String geocode = Geohash.encode(userAddress.getLat(), userAddress.getLng());
            Long areaPoint = Geohash.getArea(userAddress.getLat(), userAddress.getLng());
            latLng = ",lat=" + userAddress.getLat() + ",lng=" + userAddress.getLng() + ",geocode = '" + geocode + "',areaPoint=" + areaPoint;
        }

        String agentId = "";
        if (ValidateUtil.isID(userAddress.getAgentId())) {
            agentId = " ,agentId=" + userAddress.getAgentId();
        }

        if (ValidateUtil.isID(userAddress.getShopId())) {
            agentId += " ,shopId=" + userAddress.getShopId();
        }
        String extra1 = "";
        if (ValidateUtil.isNotNull(userAddress.getExtra1())) {
            extra1 = ",extra1='" + userAddress.getExtra1() + "'";
        }
        String sex = "";
        if (ValidateUtil.isNotNull(userAddress.getSex())) {
            sex = ",sex='" + userAddress.getSex() + "'";
        }
        if (ValidateUtil.isNotNull(userAddress.getPostalCode())) {
            sex = ",postalCode='" + userAddress.getPostalCode() + "'";
        }
        String extra2 = "";
        if (ValidateUtil.isNotNull(userAddress.getExtra2())) {
            extra2 = ",extra2='" + userAddress.getExtra2() + "'";
        }
        String extra3 = "";
        if (ValidateUtil.isNotNull(userAddress.getExtra3())) {
            extra3 = ",extra3='" + userAddress.getExtra3() + "'";
        }
        String isDefaultStr = "";
        if (userAddress.getIsDefault() == 0) {
            extra3 = ",extra3='" + userAddress.getExtra3() + "'";
        }
        String agentAddressStr = "";
        if (userAddress.getAgentAddressId() != null) {
            agentAddressStr += ", agentAddressId = " + userAddress.getAgentAddressId();
        }
        // user address
        // yangtk 2019年6月5日15:57:08
        if (ValidateUtil.isNull(userAddress.getAddress2())) {
            userAddress.setAddress2("");
        }
        if (ValidateUtil.isNull(userAddress.getAddress3())) {
            userAddress.setAddress3("");
        }
        // end
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.UserAddress).append(" set buyer = '").append(userAddress.getBuyer())
                .append("',telephone = '").append(userAddress.getTelephone())
                .append("',address = '").append(userAddress.getAddress()).append("',address3='").append(userAddress.getAddress3())
                .append("',province = '").append(userAddress.getProvince())
                .append("',city = '").append(userAddress.getCity())
                .append("',county = '").append(userAddress.getCounty())
                .append("',updateUser = '").append(user.getUsername()).append("'")
                .append(",address2='").append(userAddress.getAddress2()).append("'").append(latLng).append(agentId)
                .append(extra1).append(extra2).append(extra3).append(sex)
                .append(agentAddressStr)
                .append(",isDefault=").append(userAddress.getIsDefault())
                .append(" where id = '").append(userAddress.getId()).append("' and delflag = 0 ");

        // 默认地址处理
        List<UserAddress> userAddressList = UserAddressMemory.getInstance().listOfUser(user.getUsername());
        List<UserAddress> defaultUserAddressList = new ArrayList<>();
        if (userAddress.getIsDefault() == 1 && ValidateUtil.isAbsList(userAddressList)) {
            if (ValidateUtil.isAbsList(userAddressList)) {
                for (UserAddress u : userAddressList) {
                    if (u != null && u.getIsDefault() == 1) {
                        defaultUserAddressList.add(u);
                    }
                }
            }
        }
        Connection con = null;
        try {
            con = UserDaoSql.getInstance().getConnection();
            con.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return MultilingualResult.errorResultV2(PROMPTS.INFORMATION_SAVE_FAILED, lang);
        }
        try {
            if (defaultUserAddressList.size() > 0) {
                cancelDefaultAddress(user.getUsername(), user.getUsername(), con);
            }
            UserDaoSql.getInstance().executeBySql(sql.toString(), con);
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(con);
            return MultilingualResult.errorResultV2(PROMPTS.INFORMATION_SAVE_FAILED, lang);
        } finally {
            UserDaoSql.getInstance().close(con);
        }
        //处理缓存
        UserAddressMemory.getInstance().modifyUserAddress(userAddress.getId());
        if (defaultUserAddressList.size() > 0) {
            for (UserAddress u : defaultUserAddressList) {
                UserAddressMemory.getInstance().modifyUserAddress(u.getId());
            }
        }
        return AjaxResult.successResult();
    }


    //删除收货地址
    @RequestMapping(method = RequestMethod.POST, value = "/user/address/delete")
    @ResponseBody
    public String deleteUserAddress(String token, Long id, String ids, String lang) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        Set<Long> userAddressIdSet = new HashSet<>();
        if (ValidateUtil.isID(id)) {
            userAddressIdSet.add(id);
        } else if (ValidateUtil.isNotNull(ids)) {
            userAddressIdSet = CommonUtils.splitToSet(ids, Long.class);
        }
//         if (null == id || id <= 0) {
//             return MultilingualResult.errorResultV2(PROMPTS.CHOOSE_YOUR_ADDRESS, lang);
//         }
//         StringBuilder sql = new StringBuilder();
//         sql.append("delete from ").append(PojoTables.UserAddress).append(" where id = ").append(id);
//         try {
//             UserDaoSql.getInstance().executeBySql(sql.toString());
//         } catch (SQLException e) {
//             e.printStackTrace();
// //            return AjaxResult.errorResult("删除收货地址失败,请稍后再试");
//             return MultilingualResult.errorResultV2(PROMPTS.FAILED_DELETE_ADDRESS, lang);
//         }
//
//         //处理缓存
//         UserAddressMemory.getInstance().deleteUserAddress(id);
        if (null == userAddressIdSet || userAddressIdSet.isEmpty()) {
            return MultilingualResult.errorResultV2(PROMPTS.CHOOSE_YOUR_ADDRESS, lang);
        }
        StringBuilder sql = new StringBuilder();
        sql.append("update ").append(PojoTables.UserAddress).append(" set delFlag = 1 where id in (")
                .append(StringUtils.join(userAddressIdSet, ",")).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return MultilingualResult.errorResultV2(PROMPTS.FAILED_DELETE_ADDRESS, lang);
        }
        // cache
        for (Long tId : userAddressIdSet) {
            UserAddressMemory.getInstance().deleteUserAddress(tId);
        }
        return AjaxResult.successResult();
    }


    //设置默认收货地址
    @RequestMapping(method = RequestMethod.POST, value = "/user/address/setDefault")
    @ResponseBody
    public String setDefaultUserAddress(String token, Long id, String lang) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (null == id || id <= 0) {
            return MultilingualResult.errorResultV2(PROMPTS.CHOOSE_YOUR_ADDRESS, lang);
        }


        //取消之前默认地址
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ").append(PojoTables.UserAddress)
                .append(" set isDefault = 0,updateUser = '").append(user.getUsername())
                .append("' where username = '").append(user.getUsername())
                .append("' and isDefault = 1 and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return MultilingualResult.errorResultV2(PROMPTS.FAILED_CHANGE_DEFAULT_ADDRESS, lang);
        }

        //设置新的默认地址
        StringBuilder sql2 = new StringBuilder();
        sql2.append("UPDATE ").append(PojoTables.UserAddress)
                .append(" set isDefault = 1,updateUser = '").append(user.getUsername())
                .append("' where id = ").append(id);
        try {
            UserDaoSql.getInstance().executeBySql(sql2.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return MultilingualResult.errorResultV2(PROMPTS.FAILED_CHANGE_DEFAULT_ADDRESS, lang);
        }


        //处理缓存
        UserAddressMemory.getInstance().setUserDefaultAddress(user.getUsername(), id);

        return AjaxResult.successResult();
    }

    //``````````````````````````````````````````````````````非业务成  封装层
    //验证用户输入
    private void validateInfo(UserAddressDBVO userAddress) throws Exception {
        if (ValidateUtil.isNull(userAddress.getBuyer())) {
            throw new Exception("收货人姓名不能为空");
        }
        if (ValidateUtil.isNull(userAddress.getAddress())) {
            throw new Exception("收货人地址不能为空");
        }
        if (ValidateUtil.isNull(userAddress.getTelephone())) {
            throw new Exception("收货人联系电话不能为空");
        }
    }

    // 取消默认地址
    private static ResultInfo cancelDefaultAddress(String username, String updateUser, Connection conn) throws SQLException {
        if (StringUtils.isEmpty(username)) {
            return new ResultInfo("用户账号不能为空");
        }
        if (conn == null) {
            return new ResultInfo("数据库异常。。。。");
        }
        if (StringUtils.isEmpty(updateUser)) {
            updateUser = username;
        }
        //取消之前默认地址
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ").append(PojoTables.UserAddress)
                .append(" set isDefault = 0,updateUser = '").append(username)
                .append("' where username = '").append(updateUser)
                .append("' and isDefault = 1 and delFlag = 0");
//        try {
        UserDaoSql.getInstance().executeBySql(sql.toString(), conn);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            UserDaoSql.getInstance().rollback(conn);
//            return new ResultInfo(e.getMessage());
//        }
        // 成功
        return new ResultInfo();
    }


}
